package com.example.gobang.game;

import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChatRoom {

    private String roomId;

    private final List<WebSocketSession> players = new ArrayList<>();

    private ObjectMapper objectMapper = new ObjectMapper();

    public ChatRoom(String roomId) {
        this.roomId = roomId;
    }

    public String getRoomId() {
        return roomId;
    }

    public List<WebSocketSession> getPlayers() {
        return players;
    }

    public void addPlayer(WebSocketSession player) {
        players.add(player);
    }

    public void removePlayer(WebSocketSession player) {
        players.remove(player);
    }

    public void broadcastMessage(String sender, String content) throws IOException {
        for (WebSocketSession player : players) {
            ChatResponse resp = new ChatResponse();
            resp.setOk(true);
            resp.setSender(sender);
            resp.setContent(content);
            player.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
        }
    }
}
